package top.maof.book.controller;

import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.maof.book.annotation.Hot;
import top.maof.book.aspect.HotAspect;
import top.maof.book.model.Book;
import top.maof.book.model.Role;
import top.maof.book.model.Shelf;
import top.maof.book.result.ApiResponse;
import top.maof.book.result.PageData;
import top.maof.book.result.PageWrap;
import top.maof.book.result.Result;
import top.maof.book.service.BookInfoService;
import top.maof.book.service.ShelfService;
import top.maof.book.type.HotType;
import top.maof.book.utils.JWTUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by CodeX4J.
 */
@Controller
@RequestMapping("shelf")
@ResponseBody
public class ShelfController {
    @Autowired
    ShelfService shelfService;


    @Autowired
    BookInfoService bookInfoService;

    @ApiOperation("新建")
    @PostMapping("/create")
    @RequiresRoles({Role.ADMIN})
    public ApiResponse create(@RequestBody Shelf shelf) {
        return ApiResponse.success(shelfService.save(shelf));
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID删除")
    @GetMapping("/delete/{id}")
    public ApiResponse deleteById(@PathVariable Integer id) {
        shelfService.removeById(id);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("批量删除")
    @GetMapping("/delete/batch")
    public ApiResponse deleteByIdInBatch(@RequestParam String ids) {
        String[] idArray = ids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        shelfService.removeBatchByIds(idList);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("根据ID修改")
    @PostMapping("/updateById")
    public ApiResponse updateById(@RequestBody Shelf shelf) {
        shelfService.updateById(shelf);
        return ApiResponse.success(null);
    }

    @RequiresRoles({Role.ADMIN})
    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse<PageData<Shelf>> findPage(@RequestBody PageWrap<Shelf> pageWrap) {
        return ApiResponse.success(shelfService.findPage(pageWrap));
    }

    @PostMapping("")
    @RequiresRoles(value = {Role.ADMIN})
    public Result add(Shelf shelf) throws Exception {
        int add = shelfService.add(shelf);
        if (add > 0) {
            return Result.success();
        }
        return Result.response_500();
    }

    @RequiresRoles(value = {Role.ADMIN})
    @GetMapping("/{id}")
    public Result find(@PathVariable("id") int id) throws Exception {
        Shelf shelf = shelfService.find(id);
        return Result.success(shelf);
    }

    @RequiresRoles(value = {Role.ADMIN})
    @PutMapping("")
    public Result update(Shelf shelf) throws Exception {
        int update = shelfService.update(shelf);
        if (update > 0) {
            return Result.success();
        }
        return Result.response_500();
    }

    @RequiresRoles(value = {Role.ADMIN})
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int id) throws Exception {
        int delete = shelfService.delete(id);
        if (delete > 0) {
            return Result.success();
        }
        return Result.response_500();
    }

    @ApiOperation("获取个人书架列表")
    @GetMapping("profileShelf")
    public Result<List<Book>> getProfileShelf(@RequestHeader("token") String token) throws Exception {
        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));
        List<Book> profileShelf = shelfService.getProfileShelf(useId);
        return Result.success(profileShelf);
    }


    /**
     * 书是否在书架
     *
     * @date 2021/5/24 15:36
     */
    @ApiOperation("书是否在书架")
    @GetMapping("isExit")
    public Result has(@RequestHeader("token") String token, Integer bookId) throws Exception {
        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));
        Shelf select = shelfService.select(useId, bookId);
        if (select == null) {
            return Result.success(false);
        } else {
            return Result.success(true);
        }
    }

    @ApiOperation("移除个人书架的书")
    @GetMapping("delete")
    @Hot(value = "#bookId", type = HotType.COLLECTION, keepType = "sub")
    public Result delete(Integer bookId, @RequestHeader("token") String token) throws Exception {
        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));

        // 书架不存在此书,返回成功
        if (shelfService.select(useId, bookId) == null) return Result.success();

        shelfService.delete(useId, bookId);

        return Result.success();
    }


    @ApiOperation("移除个人书架的书")
    @GetMapping("/profile/delete")
    @Hot(value = "#bookId", type = HotType.COLLECTION, keepType = "sub")
    public Result profileDelete(Integer bookId, @RequestHeader("token") String token) throws Exception {
        int useId = Integer.parseInt(JWTUtils.parseToken(token, "id"));

        // 书架不存在此书,返回成功
        if (shelfService.select(useId, bookId) == null) return Result.success();

        shelfService.delete(useId, bookId);

        return Result.success();
    }

    @ApiOperation("添加个人书架的书")
    @GetMapping("/profile/add")
    @Hot(value = "#bookId", type = HotType.COLLECTION, keepType = "add")
    public Result profileAdd(Integer bookId, @RequestHeader("token") String token) throws Exception {
        int useId = JWTUtils.getUserId(token);
        // 有的话直接成功
        if (shelfService.select(useId, bookId) != null) return Result.success();
        Shelf shelf = new Shelf();
        shelf.setBookId(bookId);
        shelf.setUserId(useId);
        shelf.setInsertDate(new Date());
        shelfService.add(shelf);
        bookInfoService.addCollection(bookId, 1);
        return Result.success();
    }



    @ApiOperation("添加个人书架的书")
    @GetMapping("add")
    @Hot(value = "#bookId", type = HotType.COLLECTION, keepType = "add")
    public Result add(Integer bookId, @RequestHeader("token") String token) throws Exception {
        int useId = JWTUtils.getUserId(token);
        // 有的话直接成功
        if (shelfService.select(useId, bookId) != null) return Result.success();
        Shelf shelf = new Shelf();
        shelf.setBookId(bookId);
        shelf.setUserId(useId);
        shelf.setInsertDate(new Date());
        shelfService.add(shelf);
        bookInfoService.addCollection(bookId, 1);
        return Result.success();

    }

    // 获取书的收藏量
    @GetMapping("shelfNum")
    @ApiOperation("获取书的收藏量")
    public Result bookCount(Integer bookId) throws Exception {
        int i = shelfService.shelfNum(bookId);
        return Result.success(i);
    }

}
